Vue.component('app-header', {
  template: `
    <el-header class="header">
      <nav class="nav-top">
        <el-menu mode="horizontal" background-color="transparent" text-color="black"
                 active-text-color="#ffd04b">
           <el-menu-item index="1" @click="goToPage('index.html')">首页</el-menu-item>
           <el-menu-item index="2" @click="goToPage('my-user.html')">个人中心</el-menu-item>
           <el-menu-item index="3" @click="goToPage('my-rentals.html')">正在租用</el-menu-item>
           
           <!-- 添加搜索框 -->
           <el-menu-item index="4">
             <el-input
               placeholder="搜索游戏"
               v-model="searchQuery"
               @keyup.enter.native="handleSearch"
               class="search-input"
               clearable
               @click.native.stop
               >
               <i 
                 slot="prefix" 
                 class="el-icon-search" 
                 @click.stop="handleSearch"
                 style="cursor: pointer;">
               </i>
             </el-input>
           </el-menu-item>

          <div style="float: right" class="right-menu">
            <div v-if="!isLoggedIn">
              <el-button type="text"  @click="goToPage('login.html')">登录</el-button>
              <el-button type="text"  @click="goToPage('register.html')">注册</el-button>
            </div>
            <el-dropdown v-else class="avatar-container right-menu-item" trigger="click">
              <div>
                <img :src="userAvatar" alt="" style="width: 30px; border-radius: 50%; width: 30px; vertical-align: middle;">
                {{ userName }}
              </div>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item divided>
                  <span style="display:block;" @click="handlePwdUpdate()">修改密码</span>
                </el-dropdown-item>
                <el-dropdown-item divided>
                  <a href="/logout"><span style="display:block;">退出</span></a>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </div>
        </el-menu>
      </nav>
         <!-- 修改密码标签弹层 -->
        <div class="add-form">
          <el-dialog title="修改密码" :visible.sync="dialogFormVisiblePwd" :modal="false">
            <el-form ref="dataPwdForm" :model="formData" :rules="rules" label-position="right" label-width="100px">
              <el-row>
                <el-col>
                  <el-form-item prop="password">
                    <el-input type="password" v-model="formData.password" auto-complete="off"
                      placeholder="密码"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col>
                  <el-form-item prop="confirmPassword">
                    <el-input type="password" v-model="formData.confirmPassword" auto-complete="off"
                      placeholder="确认密码"></el-input>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogFormVisiblePwd = false">取消</el-button>
              <el-button type="primary" @click="handlePwd()">确定</el-button>
            </div>
          </el-dialog>
        </div>
    </el-header>
  `,
  data() {
    const validateConfirmPassword = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入确认密码'));
      } else if (value !== this.formData.password) {
        callback(new Error('两次输入的密码不一致'));
      } else {
        callback();
      }
    };
    return {
      dialogFormVisiblePwd: false,
      rules: {
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        confirmPassword: [
          { required: true, message: "请输入确认密码", trigger: "blur" },
          { validator: validateConfirmPassword, trigger: "blur" }
        ]
      },
      formData: {},
      isLoggedIn: false,
      userAvatar: '../img/head_img.png',
      userName: '啊实打实',
      searchQuery: '',
    }
  },
  created() {
    this.checkLoginStatus();
  },
  methods: {
    goToPage(htmlName) {
      window.location.href = htmlName;
    },
    // 弹出编辑窗口
    handlePwdUpdate() {
      this.formData = {};
      this.dialogFormVisiblePwd = true;
    },
    // 修改密码
    handlePwd() {
      this.$refs.dataPwdForm.validate((valid) => {
        if (valid) {
          axios.post("/com/updatePwd?password=" + this.formData.confirmPassword).then((res) => {
            console.log(res.data);
            if (res.data) {
              this.$message({
                message: '恭喜你，修改成功',
                type: 'success'
              });
              this.dialogFormVisiblePwd = false;
              this.findPage();
            }
          }).catch((error) => {
            if (error == "Error: Request failed with status code 403") {
              this.$message.error("无操作权限");
            }
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    checkLoginStatus() {
      // 假设后端提供一个API来检查登录状态
      axios.get('/com/checkLogin')
        .then(response => {
          if (response.data.success) {
            this.isLoggedIn = true;
            this.userName = response.data.data;
          } else {
            this.isLoggedIn = false;
          }
        })
        .catch(error => {
          console.error('检查登录状态失败:', error);
          this.isLoggedIn = false;
        });
    },
    handleSearch() {
      if (this.searchQuery.trim()) {
        // 如果当前不在首页，跳转到首页并带上搜索参数
        if (!window.location.pathname.endsWith('index.html')) {
          window.location.href = `index.html?search=${encodeURIComponent(this.searchQuery.trim())}`;
        } else {
          // 如果在首页，触发自定义事件
          this.$emit('search', this.searchQuery.trim());
        }
      }
    }
  }
});